/**
 * 
 */
package com.littleken.browser;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.littleken.browser.utils.SimpleResponse;
import com.littleken.core.config.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;



@RestController
@Slf4j
public class BrowserSecurityController {

	private RequestCache requestCache = new HttpSessionRequestCache();//request缓存

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();//用于处理登录跳转

	@Autowired
	private SecurityProperties properties;

	/**
	 * 没登录跳转
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	//@RequestMapping("/authentication/require")
	@GetMapping("/authentication/require")
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)//当登录没有权限时，返回401
	public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

		SavedRequest savedRequest = requestCache.getRequest(request, response);//拿到请求的缓存

		if (savedRequest != null) {
			String targetUrl = savedRequest.getRedirectUrl();
			if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {//如果请求结尾是html
				//如果请求页面是html，跳转
				redirectStrategy.sendRedirect(request, response, properties.getBrowser().getLoginPage());//跳转到默认登录页面
			}
		}

		return new SimpleResponse("访问的服务需要身份验证,请引导用户登录");
	}

}
